import { api } from '@/utils/request'

export interface StakingData {
  lockedNear: number
  stakedNear: number
  dailyRewardKRW: number
  dailyRewardNEAR: number
  totalRewardsKRW: number
  totalRewardsNEAR: number
  annualYield: number
}

export interface StakingRewards {
  totalRewards: number // D的KRW价值 (Box 2显示)
  totalRewardsNear: number // D的NEAR数量
  availableRewards: number // 可提取KRW (Box 3显示，实际是余额)
  availableRewardsNear: number // 可提取NEAR数量
  lockedRewards: number // 保留字段，现在为0
  dailyRewards: number // 预计每日收益KRW
  dailyRewardsNear: number // 预计每日收益NEAR
  apy: number // 年化收益率(%)
  dailyRate: number // 日收益率(%)
  stakingPeriod: number
}

export interface TransactionHistory {
  id: string
  type: 'stake' | 'unstake' | 'reward' | 'transfer'
  amount: number
  currency: string
  status: 'completed' | 'pending' | 'failed'
  timestamp: number
  txHash?: string
}

export interface StakingPerformance {
  validatorRank: number
  validatorName: string
  uptime: number
  commission: number
  delegators: number
  totalStaked: number
}

export interface WithdrawResult {
  success: boolean
  txHash?: string
  message: string
}

class StakingApiService {
  /**
   * 获取质押概览数据
   */
  async getStakingData(): Promise<StakingData> {
    try {
      const response = await api.get<StakingData>('/api/staking/overview')
      return response.data
    } catch (error) {
      console.error('스테이킹 데이터 조회 실패:', error)
      throw new Error('스테이킹 데이터를 불러오지 못했습니다')
    }
  }

  /**
   * 获取质押奖励信息
   */
  async getStakingRewards(): Promise<StakingRewards> {
    try {
      const response = await api.get<StakingRewards>('/api/staking/rewards')
      return response.data
    } catch (error) {
      console.error('스테이킹 보상 조회 실패:', error)
      throw new Error('보상 데이터를 불러오지 못했습니다')
    }
  }

  /**
   * 获取质押历史
   */
  async getTransactionHistory(page: number = 1, limit: number = 20): Promise<{
    transactions: TransactionHistory[]
    pagination: {
      page: number
      limit: number
      total: number
    }
  }> {
    try {
      const response = await api.get<{
        transactions: TransactionHistory[]
        pagination: {
          page: number
          limit: number
          total: number
        }
      }>('/api/staking/history', {
        params: { page, limit }
      })
      return response.data
    } catch (error) {
      console.error('스테이킹 내역 조회 실패:', error)
      throw new Error('내역 데이터를 불러오지 못했습니다')
    }
  }

  /**
   * 获取质押性能指标
   */
  async getStakingPerformance(): Promise<StakingPerformance> {
    try {
      const response = await api.get<StakingPerformance>('/api/staking/performance')
      return response.data
    } catch (error) {
      console.error('스테이킹 성과 조회 실패:', error)
      throw new Error('성과 데이터를 불러오지 못했습니다')
    }
  }

  /**
   * 提取奖励
   */
  async withdrawRewards(amount: number): Promise<WithdrawResult> {
    try {
      const response = await api.post<WithdrawResult>('/api/staking/withdraw', {
        amount
      })
      return response.data
    } catch (error) {
      console.error('보상 출금 실패:', error)
      throw new Error('출금 작업에 실패했습니다')
    }
  }

  /**
   * 锁定NEAR
   */
  async lockNear(amount: number): Promise<{ success: boolean; message?: string }> {
    try {
      const response = await api.post<{ success: boolean; message?: string }>('/api/staking/lock', {
        amount
      })
      return response.data
    } catch (error) {
      console.error('NEAR 잠금 실패:', error)
      throw new Error('잠금 작업에 실패했습니다')
    }
  }
}

export const stakingApiService = new StakingApiService()
